from fastapi import FastAPI, HTTPException
from tortoise.exceptions import DoesNotExist
from pydantic import BaseModel
from typing import List
import redis.asyncio as redis
from datetime import datetime
from models.user import User
from models.products import Product
from models.purchaseHistory import PurchaseHistory
from models.payment import OrderFake
from fastapi import APIRouter

router = APIRouter(tags=["购买历史"])
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)


class ProductResponse(BaseModel):
    id: int
    name: str
    description: str | None
    price: float
    image_url: str
    video_url: str
    inventory: int
    sales: int
    is_active: bool
    is_hot: bool
    share_count: int
    created_time: datetime
    updated_time: datetime

    class Config:
        from_attributes = True


class HistoryResponse(BaseModel):
    id: int
    user_id: int
    product_id: int
    created_time: datetime
    updated_time: datetime
    browse_time: datetime
    product: ProductResponse

    class Config:
        from_attributes = True


class OrderResponse(BaseModel):
    id: int
    order_number: str
    status: str
    total_amount: float
    actual_amount: float
    created_at: datetime

    class Config:
        from_attributes = True


class OrdersResponse(BaseModel):
    id: int
    user_id: int
    product_id: int
    order_fake_id: int | None  # 添加订单ID字段
    created_time: datetime
    updated_time: datetime
    browse_time: datetime
    product: ProductResponse
    order_fake: OrderResponse | None  # 修改为 order_fake 字段

    class Config:
        from_attributes = True


# 购买记录提交
@router.post("/api/purchase/{user_id}/{product_id}/{order_id}", response_model=OrdersResponse)
async def record_purchase(user_id: int, product_id: int, order_id: int):
    try:
        user = await User.get(id=user_id)
        product = await Product.get(id=product_id)
        order = await OrderFake.get(id=order_id)

        # 检查订单是否属于该用户
        if order.user_id != user_id:
            raise HTTPException(status_code=403, detail="订单与用户不匹配")

        # 创建购买记录（使用 PurchaseHistory 模型）
        purchase_history = await PurchaseHistory.create(
            user=user,
            product=product,
            order_fake=order,
            browse_time=datetime.now()
        )

        # 预加载产品和订单信息
        purchase_history_with_related = await PurchaseHistory.filter(id=purchase_history.id) \
            .prefetch_related("product", "order_fake") \
            .first()

        # 更新Redis浏览记录
        await redis_client.zadd(f"history:{user_id}", {product_id: datetime.now().timestamp()})

        return purchase_history_with_related

    except DoesNotExist:
        raise HTTPException(status_code=404, detail="用户、商品或订单不存在")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 购买记录查询
@router.get("/api/order/{order_id}/history", response_model=List[OrdersResponse])
async def get_order_history(order_id: int):
    try:
        order = await OrderFake.get(id=order_id)

        # 查询该订单下的所有购买记录（使用 PurchaseHistory 模型）
        history_records = await PurchaseHistory.filter(order_fake=order) \
            .prefetch_related("product", "order_fake") \
            .order_by("-browse_time")

        return history_records

    except DoesNotExist:
        raise HTTPException(status_code=404, detail="订单不存在")